import { handleShopUserprofileStatus } from '@/common/service';
import { useState, useCallback } from "react";
import Taro from "@tarojs/taro";
import { IResponseSuccess, IShopUserProfileStatus, USER_PROFILE_STATUS } from '@/typing';
import { handleCleanStore, handleLoginCallback, showToast } from '@/common/util';
import { RESPONSE_CODE, STORE_KEY } from '@/common/config';
import { API_URL } from '@/common/serviveApi';



const useProfileStatusAction = () => {
    const [userProfileStatus, setUserProfileStatus] = useState<USER_PROFILE_STATUS>(USER_PROFILE_STATUS.unknown);
    const [profileRemark, setProfileRemark] = useState('')
    const [wxApppsubscribe, setWxApppsubscribe] = useState(0)
    const [promptMessage, setPromptMessage] = useState<Array<string>>([])
    const [subscribeQrCodeUrl, setSubscribeQrCodeUrl] = useState('')
    const [switchStatus, setSwitchStatus] = useState(false)

    const handleInitProfileStatusPromise=():Promise<{code:number,data:any}>=>{
        return new Promise(async (resolve, reject) => {
            try {
            const profileRes = await handleShopUserprofileStatus() as IResponseSuccess<IShopUserProfileStatus>;
                if(profileRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS){
                    const code = profileRes.data.code
                    if(code ===RESPONSE_CODE.SUCCESS){
                        resolve({
                            code:code,
                            data:profileRes.data.data
                        })
                    }else {
                        resolve({
                            code:code,
                            data:null
                        })
                    }
                }
            } catch (error) {
                
            }
        })
    }
    const handleInitProfileStatus = useCallback(async () => {
        handleInitProfileStatusPromise().then((res)=>{
            if(res.code ===RESPONSE_CODE.SUCCESS){
                const profileRes = res.data
                const status = profileRes.status;
                const wxSubscribe = profileRes.subscribe || 0
                let subscribeQrCode = profileRes.subscribe_qr_code || ''
                const promptMessageT = profileRes.prompt_message || '预计24小时内完成审核，审核结果将通过公众号消息通知您。'
                if(promptMessageT){
                    setPromptMessage( promptMessageT.split('，'))
                    // promptMessage = promptMessageT.split(',')
                }


                const storeUserProfileStatus = Taro.getStorageSync(STORE_KEY.USER_PROFILE_STATUS) || status;
                // console.log(storeUserProfileStatus)
                if (storeUserProfileStatus === USER_PROFILE_STATUS.pending && status === USER_PROFILE_STATUS.unknown) {
                    handleCleanStore();
                } else if (storeUserProfileStatus === USER_PROFILE_STATUS.disable) {
                    const remark = profileRes.remark || ''
                    setProfileRemark(remark)

                } else if (storeUserProfileStatus === USER_PROFILE_STATUS.enable) {
                    const isTakeOrder = profileRes.is_take_orders || 0
                    if (Number(isTakeOrder) === 1) {
                        setSwitchStatus(true)
                    } else {
                        setSwitchStatus(false)
                    }

                }
                if (subscribeQrCode) {
                    subscribeQrCode = `${API_URL}${subscribeQrCode}`
                    setSubscribeQrCodeUrl(subscribeQrCode)
                }
                // setPromptMessage(promptMessageT)
                setWxApppsubscribe(wxSubscribe)

                Taro.setStorageSync(STORE_KEY.USER_PROFILE_STATUS, status);

                setUserProfileStatus(USER_PROFILE_STATUS[status]);
            }else if(res.code ===RESPONSE_CODE.LOGIN_NEED || RESPONSE_CODE.LOGIN_EXPIRE){
                handleLoginCallback(()=>handleInitProfileStatus())
            }else if (res.code === RESPONSE_CODE.ERROR) {
                throw new Error("请求异常");

            }
            else {
                showToast(res.data.msg)

            }
        })
        
    }, []);

    // useEffect(() => {
    //     const phone = Taro.getStorageSync(STORE_KEY.PHONE) || ''
    //     if (phone) {
    //         handleInitProfileStatus();
    //     }

    // }, [handleInitProfileStatus]);

    return {
        userProfileStatus,
        profileRemark,
        switchStatus,
        wxApppsubscribe,
        subscribeQrCodeUrl,
        promptMessage,
        handleInitProfileStatusPromise,
        setSwitchStatus,
        handleInitProfileStatus,
        
    };
};

export default useProfileStatusAction;
